package com.dd.common.aop.intercpt;

import com.dd.common.aop.annation.Login;
import com.dd.common.constans.TokenConstantKey;
import com.dd.common.response.ResultCode;
import com.dd.common.expection.BizException;
import com.dd.common.utils.AopUtils;
import com.dd.common.utils.JwtUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;
/**
 * 校验登录
 */
@Component
@Aspect
@Order(-1)
public class TokenAop {
    @Pointcut("@annotation(com.dd.common.aop.annation.Login)")
    public void loginPoint(){}


    @Before("loginPoint()")
    public void  inLogin(JoinPoint point){
        Method currentMethod = AopUtils.getCurrentMethod(point);
        if(Objects.isNull(currentMethod)){
            return;
        }
        boolean needLogin = currentMethod.getAnnotation(Login.class).needLogin();
        //校验token
        if(needLogin){
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(TokenConstantKey.TOKEN_KEY);
            if(Objects.isNull(token)){
                throw new BizException(ResultCode.USER_LOGIN_ERROR);
            }
            else if(JwtUtil.isTokenExpired(token)){
                throw new BizException(ResultCode.INVALID_TOKEN);
            }
        }
    }

}
